package com.nitty.cash.loop.ui.presenter

import com.nitty.cash.loop.common.CommonPresenter
import com.nitty.cash.loop.configs.NittyApiPath
import com.nitty.cash.loop.configs.NittyApiUrl
import com.nitty.cash.loop.configs.NittyApiUrl.addCommonParams
import com.nitty.cash.loop.request.IHttpCallback
import com.nitty.cash.loop.ui.contract.IViewContract
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/9/25 13:45
 * @Annotation：贷款申请 Presenter 实现
 */
class ApplyPresenter(private val iView: IViewContract.IApplyView): CommonPresenter(iView) {
    var loanDays = ""

    /**
     * 获取贷款信息
     */
    fun requestApplyDataAction(showAnim: Boolean = true){
        val params = JSONObject().addCommonParams()
        params.put("xd304965bcd9478080", NittyApiPath.NITTY_PATH.NITTY_API_LOAN_APPLY_CUSTOM_LIMIT_PATH)
        params.put("m0bb4535fe464c759",iView.getApplyAmount())
        val applyDays = iView.getApplyDays()
        if (applyDays.isNotEmpty()){
            params.put("p844196e05c6459db",applyDays)
        }
        val httpUrl = NittyApiUrl.getHttpUrl()
        doHttpPostAction(httpUrl, params,object: IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //申贷时长
                    loanDays = obj.optString("days")
                    //设置明细
                    iView.showLoadDetailsList(obj)

                    //是否允许修改申请金额，不允许修改则不显示Seekbar
                    val chooseAmountFlag = obj.optBoolean("chooseAmountFlag",false)
                    when(chooseAmountFlag){
                        true -> {//允许选择贷款额度
                            iView.showOptionalViews(obj,showAnim)
                        }
                        else -> {//不允许选择贷款额度
                            iView.showNotOptionalViews()
                        }
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView.hiddenNittyLoading()
            }
        })
    }

    /**
     * 创建贷款申请订单
     */
    fun createApplyOrderAction(){
        val params = JSONObject().addCommonParams().apply {
            put("xd304965bcd9478080", NittyApiPath.NITTY_PATH.NITTY_API_LOAN_APPLY_ORDER_CREATE_PATH)
            put("m0bb4535fe464c759",iView.getApplyAmount())
            put("p844196e05c6459db",loanDays)
        }
        val httpUrl = NittyApiUrl.getHttpUrl()
        doHttpPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                iView.hiddenNittyLoading()
                iView.showLoanApplySuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

}